/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * frmUsuario.java
 *
 * Created on 22/06/2011, 08:20:57 PM
 */
package verins.GUI;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JOptionPane;
import verins.BO.PersonaBO;
import verins.BO.PersonarnvBO;
import verins.BO.RolBO;
import verins.BO.UsuarioBO;
import verins.Utils.Comunes;
import verins.beans.Persona;
import verins.beans.Personarnv;
import verins.beans.Rol;
import verins.beans.Tipopersona;
import verins.beans.Usuario;

/**
 *
 * @author jpenam
 */
public class frmUsuario extends javax.swing.JFrame {

    /** Creates new form frmUsuario */
    
    Usuario usuario= null;
    
     public frmUsuario(Usuario u) {
        Usuario user = UsuarioBO.findById(u.getIdusuario());
        initComponents();
        setearValidadores();
        List<Rol> roles = RolBO.findAll();
        Comunes.llenarCombo(cmbRol, roles);
        verins.Utils.Comunes.centrarVentana(this);
        this.usuario=user;
        txtNombre.setText(usuario.getNombre());
        txtApellido.setText(usuario.getApellido());
        txtNombreUsuario.setText(usuario.getNombreusuario());
        txtContrasenha.setText(usuario.getContrasenha());
        txtConfContrasenha.setText(usuario.getContrasenha());
        txtCorreo.setText(usuario.getCorreo());
        cmbRol.setSelectedItem(usuario.getRol());
        txtDNI.setText(usuario.getDni());
        txtNombre.setEnabled(false);
        txtApellido.setEnabled(false);
        txtNombreUsuario.setEnabled(false);
        txtContrasenha.setEnabled(false);
        txtConfContrasenha.setEnabled(false);
        txtCorreo.setEnabled(false);
        txtDNI.setEnabled(false);
        cmbRol.setEnabled(false);
        txtDNI.setEnabled(false);
        btnEditar.setVisible(true);
        btnGuardar.setEnabled(false);

    }

     
    public frmUsuario() {
        
        initComponents();
        setearValidadores();
        verins.Utils.Comunes.centrarVentana(this);
                                 
        List<Rol> roles = RolBO.findAll();
        Comunes.llenarCombo(cmbRol, roles);
   
        btnEditar.setVisible(false);
        btnGuardar.setEnabled(true);
        txtApellido.setEnabled(false);
        txtNombre.setEnabled(false);
    }

    private void setearValidadores(){
        txtNombre.setDocument(new verins.Utils.LimitInput(100));
        txtNombre.addKeyListener(verins.Utils.Verificador.verificaSoloLetras());
        txtNombreUsuario.setDocument(new verins.Utils.LimitInput(50));
        txtNombreUsuario.addKeyListener(verins.Utils.Verificador.verificaSoloLetras());
        txtApellido.setDocument(new verins.Utils.LimitInput(100));
        txtApellido.addKeyListener(verins.Utils.Verificador.verificaSoloLetras());
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        txtNombreUsuario = new javax.swing.JTextField();
        txtNombre = new javax.swing.JTextField();
        txtApellido = new javax.swing.JTextField();
        txtCorreo = new javax.swing.JTextField();
        txtDNI = new javax.swing.JTextField();
        cmbRol = new javax.swing.JComboBox();
        btnEditar = new javax.swing.JButton();
        btnGuardar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();
        txtContrasenha = new javax.swing.JPasswordField();
        txtConfContrasenha = new javax.swing.JPasswordField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Usuarios");
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jLabel1.setText("Nombre Usuario");

        jLabel2.setText("Nombre");

        jLabel3.setText("Apellido");

        jLabel4.setText("Correo");

        jLabel5.setText("Contrasenha");

        jLabel6.setText("Confirmar");

        jLabel7.setText("Rol");

        jLabel8.setText("DNI");

        txtDNI.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtDNIFocusLost(evt);
            }
        });

        btnEditar.setText("Editar");
        btnEditar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEditarActionPerformed(evt);
            }
        });

        btnGuardar.setText("Guardar");
        btnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuardarActionPerformed(evt);
            }
        });

        btnCancelar.setText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGap(138, 138, 138)
                        .addComponent(jLabel8)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtDNI, javax.swing.GroupLayout.DEFAULT_SIZE, 254, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGap(119, 119, 119)
                        .addComponent(btnEditar, javax.swing.GroupLayout.PREFERRED_SIZE, 61, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(36, 36, 36)
                        .addComponent(btnGuardar)
                        .addGap(46, 46, 46)
                        .addComponent(btnCancelar))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGap(73, 73, 73)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel6)
                            .addComponent(jLabel5)
                            .addComponent(jLabel7))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(txtContrasenha, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 254, Short.MAX_VALUE)
                            .addComponent(cmbRol, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtConfContrasenha, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 254, Short.MAX_VALUE)))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGap(51, 51, 51)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel4)
                            .addComponent(jLabel1)
                            .addComponent(jLabel3)
                            .addComponent(jLabel2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtNombreUsuario, javax.swing.GroupLayout.DEFAULT_SIZE, 253, Short.MAX_VALUE)
                            .addComponent(txtCorreo, javax.swing.GroupLayout.DEFAULT_SIZE, 253, Short.MAX_VALUE)
                            .addComponent(txtApellido, javax.swing.GroupLayout.DEFAULT_SIZE, 253, Short.MAX_VALUE)
                            .addComponent(txtNombre, javax.swing.GroupLayout.DEFAULT_SIZE, 253, Short.MAX_VALUE))))
                .addGap(61, 61, 61))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel8)
                    .addComponent(txtDNI, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addGap(19, 19, 19)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtApellido, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtNombreUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtCorreo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(txtContrasenha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(txtConfContrasenha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(cmbRol, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 35, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnEditar)
                    .addComponent(btnGuardar)
                    .addComponent(btnCancelar))
                .addGap(29, 29, 29))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed
        // TODO add your handling code here:
        if (txtNombreUsuario.getText()==null || txtNombreUsuario.getText().equals("")){
            JOptionPane.showMessageDialog(null, "El campo Nombre Usuario es obligatorio", "Advertencia", JOptionPane.WARNING_MESSAGE);
            return;
        }
        if (txtNombre.getText()==null || txtNombre.getText().equals("")){
            JOptionPane.showMessageDialog(null, "El campo Nombre es obligatorio", "Advertencia", JOptionPane.WARNING_MESSAGE);
            return;
        }
        if (txtDNI.getText()==null || txtDNI.getText().equals("")){
            JOptionPane.showMessageDialog(null, "El campo DNI es obligatorio", "Advertencia", JOptionPane.WARNING_MESSAGE);
            return;
        }
        if (txtApellido.getText()==null || txtApellido.getText().equals("")){
            JOptionPane.showMessageDialog(null, "El campo Apellido es obligatorio", "Advertencia", JOptionPane.WARNING_MESSAGE);
            return;
        }
        if (txtCorreo.getText()==null || txtCorreo.getText().equals("")){
            JOptionPane.showMessageDialog(null, "El campo Apellido es obligatorio", "Advertencia", JOptionPane.WARNING_MESSAGE);
            return;
        }
        
        if (txtContrasenha.getText()==null || txtContrasenha.getText().equals("")){
            JOptionPane.showMessageDialog(null, "El campo Apellido es obligatorio", "Advertencia", JOptionPane.WARNING_MESSAGE);
            return;
        }
        if (!txtContrasenha.getText().equals(txtConfContrasenha.getText())){
            JOptionPane.showMessageDialog(null, "Las contraseñas deben coincidir", "Advertencia", JOptionPane.WARNING_MESSAGE);
            return;
        }
        System.out.println(txtCorreo.getText());
        /*
        if (!isEmail( txtCorreo.getText())){
            verins.Utils.Mensajes.alerta("Debe ingresar Correo válido");
            return;
        }
         */
         
        if (this.usuario==null)
            usuario = new Usuario();
        usuario.setNombre(txtNombre.getText());
        usuario.setApellido(txtApellido.getText());
        usuario.setNombreusuario(txtNombreUsuario.getText());
        usuario.setContrasenha(txtContrasenha.getText());
        usuario.setCorreo(txtCorreo.getText());
        usuario.setRol((Rol)cmbRol.getSelectedItem());
        if (verins.Utils.Mensajes.guardar(evt, this)){
           
            Personarnv personarnv = new Personarnv();
            personarnv = PersonarnvBO.findByDNI(txtDNI.getText());
            Persona persona = Comunes.convertirAPersona(personarnv);
            PersonaBO.save(persona);
            usuario.setDni(personarnv.getDni());
            if(verins.Utils.Mensajes.exito(UsuarioBO.save(usuario)))
                this.dispose();
        }
    }//GEN-LAST:event_btnGuardarActionPerformed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        // TODO add your handling code here:
         this.dispose();
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void btnEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditarActionPerformed
        // TODO add your handling code here:
        txtNombre.setEnabled(false);
        txtApellido.setEnabled(false);
       // txtDNI.setEnabled(true);
        txtNombreUsuario.setEnabled(true);
       txtContrasenha.setEnabled(true);
        txtConfContrasenha.setEnabled(true);
        txtCorreo.setEnabled(true);
        cmbRol.setEnabled(true);

        btnEditar.setVisible(false);
        btnGuardar.setEnabled(true);
    }//GEN-LAST:event_btnEditarActionPerformed

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        // TODO add your handling code here:
       
    }//GEN-LAST:event_formWindowOpened

    private void txtDNIFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtDNIFocusLost
        // TODO add your handling code here:
        Personarnv personarnv = new Personarnv();
        if(txtDNI.getText().equals(""))
            return;
        
            personarnv = new PersonarnvBO().findByDNI(txtDNI.getText());
            //Persona personarn = new Persona();
            if(personarnv == null){
                txtNombre.setText("");
                txtApellido.setText("");
                JOptionPane.showMessageDialog(null, "No se encontró la Persona Ingrese DNI correcto", "Advertencia", JOptionPane.WARNING_MESSAGE);
                return;
            }
            txtNombre.setText(personarnv.getNombres());
            txtApellido.setText(personarnv.getApepaterno()+" "+personarnv.getApematerno());
    }//GEN-LAST:event_txtDNIFocusLost

                                            

                                   

                                            

   
    public boolean isEmail(String correo) {
        Pattern pat = null;
        Matcher mat = null;
        pat = Pattern.compile("^([0-9a-zA-Z]([_.w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-w]*[0-9a-zA-Z].)+([a-zA-Z]{2,9}.)+[a-zA-Z]{2,3})$");
        mat = pat.matcher(correo);
        if (mat.find()) {
            System.out.println("[" + mat.group() + "]");
            return true;
        }else{
            return false;
        }
    }

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new frmUsuario().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnEditar;
    private javax.swing.JButton btnGuardar;
    private javax.swing.JComboBox cmbRol;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JTextField txtApellido;
    private javax.swing.JPasswordField txtConfContrasenha;
    private javax.swing.JPasswordField txtContrasenha;
    private javax.swing.JTextField txtCorreo;
    private javax.swing.JTextField txtDNI;
    private javax.swing.JTextField txtNombre;
    private javax.swing.JTextField txtNombreUsuario;
    // End of variables declaration//GEN-END:variables
}
